package com.czt.mail.util;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.time.Duration;

/**
 * @author czt
 * @date 2022/12/7 18:41
 * @description: 发送邮箱业务
 */
@Component
public class MailMsg {

    @Resource
    private JavaMailSenderImpl mailSender;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${spring.mail.username}")
    private String username;

    public boolean mail(String email) throws MessagingException {

        MimeMessage mimeMessage = mailSender.createMimeMessage();
        //生成随机验证码
        String code = CodeGeneratorUtil.randomSixNumber();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        //设置一个html邮件信息
        helper.setText("您的验证码为：" + code + "，请于五分钟内正确输入，不要把验证码告诉他人，如非本人操作，请忽略信息", true);
        //设置邮件主题名
        helper.setSubject("优医视觉营销平台登录验证码");
        //邮箱地址
        helper.setTo(email);
        //发送人邮箱
        try {
            helper.setFrom(new InternetAddress(username, "优医视觉"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        //将邮箱验证码以邮件地址为key存入redis,1分钟过期
        redisTemplate.opsForValue().set(email, code, Duration.ofMinutes(1));
        mailSender.send(mimeMessage);
        return true;
    }
}
